package hkr.se1.cyvasse;

import Game.Game;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

	private LinearLayout base;
	private BoardView boardView;
	private Game game;
	private MediaPlayer mediaPlayer;
	private BottomButtonView bottomButtonView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Hides the ActionBar.
		getActionBar().hide();
		// Locks the screen in portrait orientation.
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		// Initialize layout
		init();
	}

	@Override
	public void onPause() {
		super.onPause();
		mediaPlayer.pause();
	}

	@Override
	public void onResume() {
		super.onResume();
		mediaPlayer.start();
	}

	private void init() {
		game = new Game();
		base = new LinearLayout(this);
		base.setBackgroundResource(R.drawable.background);
		base.setGravity(Gravity.CENTER);
		base.setOrientation(LinearLayout.VERTICAL);
		boardView = new BoardView(this, game);
		setupScreen();
		bottomButtonView = new BottomButtonView(this);
		bottomButtonView.setGravity(Gravity.CENTER);

		mediaPlayer = MediaPlayer.create(this, R.raw.game_of_thrones);
		mediaPlayer.start();
		mediaPlayer.setLooping(true);

		Button button = bottomButtonView.getMakeMoveButton();
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.e("buttonClicked", "button is clicked");

				game.setupNextStep();
				reDraw();
				setupScreen();
			}

		});

		setContentView(base);
		base.addView(boardView);
		base.addView(bottomButtonView);
	}

	public void setupScreen() {
		if (game.getSetup() != Game.RUN_GAME) {
			boardView.setupScreen(game.getTurn(), true);
		} else {
			boardView.setupScreen(game.getTurn(), false);
		}
	}

	public void reDraw() {
		boardView.draw();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			moveTaskToBack(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
